package com.ddd.app.user.executor.command;

import com.ddd.app.user.assembler.UserAssembler;
import com.ddd.client.user.dto.command.UserRegisterCmd;
import com.ddd.client.user.dto.co.UserErrorCode;
import com.ddd.client.user.dto.co.UserCO;
import com.ddd.domain.user.model.entity.UserEntity;
import com.ddd.domain.user.service.UserService;
import com.ddd.infrastructure.common.exception.DddBizException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * UserRegisterCmdExe
 *
 * @author guowm
 */
@Component
public class UserRegisterCmdExe {

    @Autowired
    private UserService userService;

    public UserCO execute(UserRegisterCmd userRegisterCmd) {
        // check 用户名是否重复
        if (userService.checkByUsername(null, userRegisterCmd.getUsername())) {
            throw new DddBizException(UserErrorCode.B_USER_USERNAME_REPEAT);
        }

        UserEntity userEntity = userService.save(UserAssembler.toEntity(userRegisterCmd));

        return UserAssembler.toValueObject(userEntity);
    }
}
